import axios from 'axios'
import router from '../router'
import store from '@/../store'
// import Security from '@/common/security'
import {
  getAccessToken
} from '@/utils/auth'
import {
  Toast
} from 'vant'

// 环境的切换
axios.defaults.timeout = 5000
axios.defaults.baseURL = process.env.HOST
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 加载loading
let loadingInstance = null
// 请求拦截器
axios.interceptors.request.use(
  config => {
    if (!config.headers.Fastmode) {
      loadingInstance = Toast.loading({
        mask: true,
        duration: 0,
        position: 'middle',
        className: 'toast-loading',
        forbidClick: true
      })
    }
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断
    // const SecurityToken = Security.getAccessToken()
    // console.log('// ---- Axios Security AccessToken1:', SecurityToken)
    const token = getAccessToken()
    console.log('// ---- Axios Security AccessToken2:', token)
    token && (config.headers.Authorization = 'Bearer ' + token)
    return config
  },
  error => {
    return Promise.reject(error)
  })

// 响应拦截器
axios.interceptors.response.use(
  response => {
    loadingInstance !== null && loadingInstance.clear()
    // Do something with response data
    console.log('// ---- Axios Http Response Data:', response.data)

    store.dispatch('settings/changeSetting', {
      key: 'backRoute',
      value: {
        redirect: router.currentRoute.fullPath
      }
    })
    return Promise.resolve(response.data)
  },
  error => {
    console.log('// ---- Axios Http Response Error:', typeof error, error.response)
    loadingInstance !== null && loadingInstance.clear()
    // Do something with response error
    if (typeof error === 'object' && error && error.response) {
      switch (error.response.status) {
        case 401:
          // 401: 未授权或者授权失效
          // 移除保存的token
          store.dispatch('authorize/resetToken')
          // 未登录则跳转登录页面，并携带当前页面的路径
          // 在登录成功后返回当前页面，这一步需要在登录页操作。
          console.log('// ---- Axios 401 Router:', router)
          router.replace({
            name: 'authorize',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break
        case 402:
        case 403:
          // 403 token过期
          // 登录过期对用户进行提示
          // 清除本地token和清空vuex中token对象
          // 跳转登录页面
          loadingInstance = Toast.loading({
            mask: true,
            duration: 2500,
            message: '登录过期，请重新登录...',
            position: 'middle',
            className: 'toast-loading',
            forbidClick: true,
            onOpened: () => {
              setTimeout(() => {
                loadingInstance.message = '即将自动跳转至登录'
              }, 1000)
            },
            onClose: () => {
              // 清除token
              // localStorage.removeItem('token')
              // this.$store.commit('userInfo', null)
              // console.log('// ---- Axios 402+403 Router:', router.currentRoute.fullPath)
              // // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
              // router.push({
              //   name: 'passport/login',
              //   query: {
              //     redirect: router.currentRoute.fullPath
              //   }
              // })
              console.log('[Axios 402+403 Router]', router.currentRoute)
              if (!/\/login|\/authorize/g.test(router.currentRoute.path)) {
                // 储存来源路由
                sessionStorage.setItem('referrer', router.currentRoute.path)
              }
              // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
              router.push({
                path: '/passport/login'
              })
            }
          })
          break

        case 406:
          // 406
          Toast(error.response.data.message)
          break
        case 428:
          // 406
          Toast({
            message: error.response.data.message,
            duration: 2500,
            forbidClick: true
          })
          break
        case 418:
        case 500:
        case 404:
        case 503:
          // 404请求不存在
          router.replace({
            path: '/error',
            query: error.response
          })
          break
        default:
          Toast({
            message: error.response.data.message,
            duration: 2500,
            forbidClick: true
          })
      }
    } else {
      console.log(error.code, error.name, error.message)
      router.push({
        name: 'exception',
        query: {
          error: error.message
        }
      })
    }
    return Promise.reject(error)
  })

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} loading [是否显示加载]
 */
// const dispenseErrorHandler = (error) => {
//
// }

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} loading [是否显示加载]
 */
export function get (url, params, fastmode = true) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params,
      headers: {
        Fastmode: fastmode
      }
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        console.log('// ---- Promise Http Response Error:', err)
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} fastmode [请求时携带的参数]
 * @param {Object} config [请求时携带的参数]
 */
export function post (url, params, fastmode = false, config) {
  return new Promise((resolve, reject) => {
    let headers = Object.assign({
      Fastmode: fastmode
    }, config)
    axios.post(url, params, {
      headers: headers
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        console.log(err)
        reject(err)
      })
  })
}

export default axios
